﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using EOSCRM.Dao;
using EOSCRM.Domain;
using EOSCRM.Util;
using EOSCRM.Web.UserControls;
using EOSCRM.Web.Shared;
using System.Web.UI.WebControls;

namespace EOSCRM.Web.Common
{
    /// <summary>
    /// Summary description for Authorization
    /// </summary>
    public class Authentication : Page
    {
       
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // Authenticate
            Authenticate();
        }

        private const string _IDwhenFORWARD = "_SESSION_PARENTFUNCTION_";
        protected class ForwardINFO
        {
            public int ParentID { get; set; }
            public string ChildURL { get; set; }
        }
        protected ForwardINFO INFORwhenFORWARD
        {
            get
            {
                ForwardINFO curInfo = null;
                try { curInfo = Session[_IDwhenFORWARD] as ForwardINFO; }
                catch { }
                return curInfo;
            }
            set { Session[_IDwhenFORWARD] = value; }
        }
        class Group4Action
        {
            public int GroupID { get; set; }
            public int GroupAction { get; set; }
        }
        List<Group4Action> Group4Actions;
        public enum HasPermission
        {
            READ = 1,
            INSERT = 2,
            UPDATE = 3,
            DELETE = 4
        }

        public UserAdmin LoginInfo
        {
            get { return Session[SessionKey.USER_LOGIN] as UserAdmin; }
            set { Session[SessionKey.USER_LOGIN] = value; }
        }

        bool HasReadPermission { get; set; }
        public bool HasInsertPermission { get; set; }
        public bool HasUpdatePermission { get; set; }
        public bool HasDeletePermission { get; set; }

        protected int FunctionID { get; set; }
        protected string FunctionURL { get; set; }
        protected string FunctionFieldsLog { get; set; }

        protected string ExtractURL(string urlPath)
        {
            const string fnExt = ".aspx";

            urlPath = urlPath.Substring("http://".Length);
            urlPath = urlPath.Substring(urlPath.IndexOf('/') + 1);

            if (urlPath.IndexOf(fnExt, StringComparison.OrdinalIgnoreCase) >= 0)
                urlPath = urlPath.Substring(0, urlPath.IndexOf(fnExt, StringComparison.OrdinalIgnoreCase) + fnExt.Length);

            return urlPath;
        }

        public void Authenticate()
        {
            if (LoginInfo == null) { Context.Response.Redirect(WebUrlConstants.LOGIN_PAGE, false); return; }
            if (Master == null) { return; }

            var header = (Header)Master.FindControl("header");
            var fncDao = new FunctionDao();
            FunctionURL = ExtractURL(Request.Url.ToString());
            var curFnc = fncDao.GetFromURL(FunctionURL);

            if (curFnc != null)
            {
                FunctionID = curFnc.Id;
                Page.Title = string.Format("EOS-CRM > {0} > {1}", fncDao.GetPath(curFnc.Parent), curFnc.Name);
                if (header != null)
                {
                    header.ModuleName = fncDao.GetModuleName(curFnc.Parent);
                    header.TitlePage = fncDao.GetPageTitle(curFnc.Id);
                }
            }
            else
            {
                FunctionID = 0;
                Page.Title = Resources.Message.TITLE_TRANGCHU;
                header.ModuleName = Resources.Message.MODULE_TRANGCHU;
                header.TitlePage = Resources.Message.PAGE_TRANGCHU;
            }

            FunctionURL = "/" + FunctionURL;

            HasReadPermission =
                (FunctionURL.ToLower() == ResolveUrl(WebUrlConstants.HOME_PAGE).ToLower()) ||
                (FunctionURL.ToLower() == ResolveUrl(WebUrlConstants.CHANGEPASSWORD_PAGE).ToLower()) ||
                (FunctionURL.ToLower() == ResolveUrl(WebUrlConstants.ERROR_PAGE).ToLower());
            if (!HasReadPermission) Authenticate(HasPermission.READ);

            HasInsertPermission = checkAuthenticate(HasPermission.INSERT);
            HasUpdatePermission = checkAuthenticate(HasPermission.UPDATE);
            HasDeletePermission = checkAuthenticate(HasPermission.DELETE);


            // clear removable session 
            // check current FunctionUrl 
            if(Session["_FUNCTION_URL_"] != null && 
                Session["_FUNCTION_URL_"].ToString() != FunctionURL)
            {
                SessionManager.ClearRemovableSessionKeys();
            }

            Session["_FUNCTION_URL_"] = FunctionURL;
            // lấy thông tin phường quản lý
            
        }

        public void DoError(Message msg)
        {
            if (msg == null) return;

            Session[SessionKey.MESSAGE] = msg;

            // Redirect to error page
            Response.Redirect(WebUrlConstants.ERROR_PAGE, false);
        }

        public void Authenticate(HasPermission permission) { Authenticate(FunctionID, permission); }
        public void Authenticate(int idFunc, HasPermission permission)
        {
            if (checkAuthenticate(idFunc, permission)) return;
            var msg = new Message(MessageConstants.WARN_PERMISSION_DENIED, MessageType.Warning, Page.Title);
            DoError(msg);
        }

        bool checkAuthenticate(HasPermission permission) { return checkAuthenticate(FunctionID, permission); }
        bool checkAuthenticate(int idFunc, HasPermission permission)
        {
            //Options.AdminName
            try { if (LoginInfo.MaNV.ToLower() == "admin") return true; }
            catch { return false; }
            if (INFORwhenFORWARD != null)
            {
                if (INFORwhenFORWARD.ChildURL == FunctionURL && INFORwhenFORWARD.ParentID > 0)
                    idFunc = INFORwhenFORWARD.ParentID;
                else Session.Remove(_IDwhenFORWARD);
            }
            if (Group4Actions == null)
            {
                Group4Actions = new List<Group4Action>();
                var gpList = new GroupDao().GetGPList(idFunc, LoginInfo.MaNV);

                foreach (var gp in gpList)
                    Group4Actions.Add(new Group4Action { GroupID = gp.GroupId, GroupAction = gp.Mash });
            }
            return Group4Actions.Find(f => f.GroupAction == permission.GetHashCode()) != null;
        }

        protected void ReDirect(string urlPath) { ReDirect(FunctionID, urlPath); }
        protected void ReDirectFromParent(string urlPath)
        {
            ReDirect(INFORwhenFORWARD == null ? FunctionID : INFORwhenFORWARD.ParentID, urlPath);
        }
        void ReDirect(int idParent, string urlPath)
        {
            const string fnExt = ".aspx";
            INFORwhenFORWARD = new ForwardINFO
            {
                ParentID = idParent,
                ChildURL = urlPath.Substring(0, urlPath.IndexOf(fnExt, StringComparison.OrdinalIgnoreCase) + fnExt.Length)
            };
            Response.Redirect(urlPath, false);
        }

        public string ChiNhanhTrucThuoc
        {
            get { return Session[SessionKey.USER_CHINHANH] as string; }
            set { Session[SessionKey.USER_CHINHANH] = value; }
        }

        
        #region Startup script registeration
        public void ShowError(string message, string controlId)
        {
            ((EOS)Page.Master).ShowError(message, controlId);
        }

        public void ShowError(string message)
        {
            ((EOS)Page.Master).ShowError(message);
        }

        public void ShowInfor(string message)
        {
            ((EOS)Page.Master).ShowInfor(message);
        }

        public void UnblockDialog(string divId)
        {
            var master = (EOS)Page.Master;
            if (master != null) master.UnblockDialog(divId);
        }

        public void CloseWaitingDialog()
        {
            ((EOS)Page.Master).CloseWaitingDialog();
        }

        public void SetReadonly(string id, bool isReadonly)
        {
            ((EOS)Page.Master).SetReadonly(id, isReadonly);
        }

        public void SetControlValue(string id, string value)
        {
            ((EOS)Page.Master).SetControlValue(id, value);
        }

        public void HideDialog(string divId)
        {
            ((EOS)Page.Master).HideDialog(divId);
        }

        public void SetLabel(string id, string value)
        {
            var master = (EOS)Page.Master;
            if (master != null) master.SetLabel(id, value);
        }

        public void ShowWarning(string message)
        {
            var master = (EOS)Page.Master;
            if (master != null) master.ShowWarning(message);
        }
        
        public void UnblockWaitingDialog()
        {
            var master = (EOS)Page.Master;
            if (master != null) master.UnblockWaitingDialog();
        }

        public void FocusAndSelect(string controlId)
        {
            ((EOS)Page.Master).FocusAndSelect(controlId);
        }
        #endregion
        public void SetCheckBoxValue(CheckBox check, bool? value)
        {
            check.Checked = (value.HasValue) ? value.Value : false;
        }
        public void SetTimeTexBox(TextBox ctrol, DateTime? value, String format)
        {
            SetControlValue(ctrol.ClientID, value.HasValue ? value.Value.ToString(format) : "");
        }
        public void SetDecimalTextBox(TextBox ctrol, Decimal? value)
        {
            SetControlValue(ctrol.ClientID, value.HasValue ? value.Value.ToString() : "");
        }
        public void SetIntToConTrol(TextBox ctrol, Int32? value)
        {
            SetControlValue(ctrol.ClientID, value.HasValue ? value.Value.ToString() : "");
        }
        public void SetDropListValue(DropDownList ddl, string value)
        {
            if (String.IsNullOrEmpty(value))
            {
                ddl.SelectedIndex = 0;
                return;
            }
            var item = ddl.Items.FindByValue(value);
            if (item != null)
                ddl.SelectedIndex = ddl.Items.IndexOf(item);
            else
                ddl.SelectedIndex = 0;
        }

        public void SetDateTextBox(TextBox txt, DateTime? value)
        {
            txt.Text = value.HasValue ? value.Value.ToString("dd/MM/yyyy") : "";
        }

        public void SetChecked(CheckBox cb, bool? value)
        {
            cb.Checked = value.HasValue && value.Value;
        }
        //public List<String> KhuVucQuanLys
        //{
        //    get
        //    {
        //        return Session[SessionKey.KHUVUCQUANLY] as List<String>;
        //    }
        //    set
        //    {
        //        Session[SessionKey.KHUVUCQUANLY] = value;
        //    }
        //}

        public string ComputerName
        {
            get
            {
                return Session["ComputerName"] as String;
            }
            set
            {
                Session["ComputerName"] = value;
            }

        }
        public string IpAdress
        {
            get
            {
                return Session["IpAdress"] as String;
            }
            set
            {
                Session["IpAdress"] = value;
            }
        }
        public string NgayThangNamNow()
        {
            return String.Format("{0}, ngày {1} tháng {2} năm {3}", "Bình Phước", DateTime.Now.Day.ToString("D2"),
                DateTime.Now.Month.ToString("D2"),
                DateTime.Now.Year.ToString("D4"));
        }
        public string NgayThangNam(TextBox obj)
        {
            var date = ConvertUtil.ToDateTime(obj.Text.Trim());
            if (date.HasValue)
            {
                return String.Format("{0}, ngày {1} tháng {2} năm {3}", "Bình Phước", date.Value.Day.ToString("D2"),
                date.Value.Month.ToString("D2"),
                date.Value.Year.ToString("D4"));
            }
            return String.Format("{0}, ngày {1} tháng {2} năm {3}", "Bình Phước", DateTime.Now.Day.ToString("D2"),
                DateTime.Now.Month.ToString("D2"),
                DateTime.Now.Year.ToString("D4"));
        }
        public string MaKhuVuc
        {
            get
            {
                return Session[SessionKey.MaKhuVuc] as string;
            }
            set
            {
                Session[SessionKey.MaKhuVuc] = value;
            }
        }
    }
}